<?php
namespace App\Service\H5;

class StaffService extends BaseService
{
    //人员管理

    //人员列表
    public static function index($pas)
    {
        $db = self::dbConn(self::$dbStaff); //->where('is_able', 0);
        // if ($pas['role_id'] && $pas['role_id']>2) {
        //     $db = $db->where('role_id', $pas['role_id']);
        // }
        // if ($pas['depart_id']) {
        //     $db = $db->where('depart_id', $pas['depart_id']);
        // }
        $total = $db->count();
        $res = $db->get();
        if (!count($res)) {
            return self::toback(-2, '员工不存在');
        }
        $arys = [];
        foreach ($res as $v) {
            $roleOne = self::dbConn(self::$dbStRole)
                ->where('id', $v->role_id)
                ->first();
            $role_name = empty($roleOne) ? '-' : $roleOne->title;
            $departOne = self::dbConn(self::$dbStDepart)
                ->where('id', $v->depart_id)
                ->first();
            $depart_name = empty($departOne) ? '-' : $departOne->title;
            // $depart_name = $v->depart_lead==2 ? $depart_name.'【领导】' : $depart_name.'【成员】';
            $lead_name = $v->depart_lead==2 ? '领导' : '成员';
            $staus_name = $v->is_able ? '禁用' : '正常';
            $arys[] = [
                'uid' => $v->id, 'uname' => $v->title,
                'role_id' => $v->role_id, 'role_name' => $role_name,
                'depart_id' => $v->depart_id, 'depart_name' => $depart_name,
                'lead_id' => $v->depart_lead, 'lead_name' => $lead_name,
                'status' => $v->is_able, 'status_name' => $staus_name,
                'lasttime' => $v->uptime,
            ];
        }
        return self::toback(0, '', $arys, $total);
    }

    // 获取详情
    public static function getOne($id)
    {
        $arys = ['data' => [], 'depart' => [], 'lead' => [], 'role' => [], 'able' => []];
        // 人员数据
        $res = (array) self::dbConn(self::$dbStaff)
            ->select('id', 'title', 'depart_id', 'depart_lead', 'role_id', 'is_able')
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            $res = [
                'id' => 0, 'title' => '', 'depart_id' => 0, 
                'depaer_lead' => 0, 'role_id' => 0, 'is_able' => 0,
            ];
        }
        $arys['data'] = $res;
        // 部门
        $arys['depart'] = self::dbConn(self::$dbStDepart)
            ->where('del', 0)
            ->get();
        // 角色
        $arys['role'] = self::dbConn(self::$dbStRole)
            ->where('del', 0)
            ->get();
        // 身份
        $arys['lead'] = [
            ['id' => 1, 'title' => '普通员工'],
            ['id' => 2, 'title' => '部门领导'],
        ];
        // 禁用
        $arys['able'] = [
            ['id' => 0, 'title' => '正常'],
            ['id' => 1, 'title' => '禁用'],
        ];
        return $arys;
    }

    //状态
    public static function modify($id, $pas)
    {
        $res = self::dbConn(self::$dbStaff)->where('id', $id)->first();
        if (!$res) {
            return self::toback(-2, '员工不存在');
        }
        $pas['uptime'] = toDate();
        $res = self::dbConn(self::$dbStaff)->where('id', $id)->update($pas);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    // 设置密码
    public static function setPwd($id, $pas)
    {
        $res = (array) self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return self::toback(-2, '没有数据');
        }
        if ($res['passwd'] != md5($pas['upwd'])) {
            return self::toback(-2, '原密码错误');
        }
        $res = self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->update(['passwd' => md5($pas['pwdnew']), 'uptime' => toDate()]);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    // 设置密码
    public static function setPasswd($id, $pas)
    {
        $res = (array) self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return self::toback(-2, '没有数据');
        }
        if ($res['passwd'] != md5($pas['pwd'])) {
            return self::toback(-2, '原密码错误');
        }
        $res = self::dbConn(self::$dbStaff)
            ->where('id', $id)
            ->update(['passwd' => md5($pas['pwdnew']), 'uptime' => toDate()]);
        if (!$res) {
            return self::toback(-1, 'error');
        }
        return self::toback();
    }

    //登录
    public static function dologin($uname, $upwd)
    {
        $loginMsg = ['uname' => $uname, 'upwd' => $upwd];
        $uOne = self::dbConn(self::$dbStaff)
            ->where('title', $uname)
            ->first();
        if (empty($uOne)) {
            self::addLog($loginMsg, 0, '员工不存在');
            return self::toback(-2, '员工不存在');
        }
        if ($uOne->is_able > 0) {
            self::addLog($loginMsg, 0, '员工被禁用');
            return self::toback(-2, '员工被禁用');
        }
        if ($uOne->passwd != md5($upwd)) {
            self::addLog($loginMsg, $uOne->id, '密码错误');
            return self::toback(-2, '密码错误');
        }
        self::addLog($loginMsg, $uOne->id, '登录成功');
        $roleOne = self::dbConn(self::$dbStRole)
            ->where('id', $uOne->role_id)
            ->first();
        $role_name = empty($roleOne) ? '' : $roleOne->title;
        $departOne = self::dbConn(self::$dbStDepart)
            ->where('id', $uOne->depart_id)
            ->first();
        $depart_name = empty($departOne) ? '' : $departOne->title;
        $depart_name = $uOne->depart_lead==2 ? $depart_name.'成员' : $depart_name.'员工';
        $ary = [
            'uid' => $uOne->id, 'uname' => $uname,
            'role_id' => $uOne->role_id, 'role_name' => $role_name,
            'depart_id' => $uOne->depart_id, 'depart_name' => $depart_name,
            'logtime' => date('Ymd', time()),
            'is_leader' => $uOne->depart_lead>1 ? 1 : 0,
        ];
        return self::toback(0, '', $ary);
    }

    //登录日志
    public static function addLog($loginMsg = [], $uid = 0, $errMsg = '')
    {
        //$loginMsg = json_encode($loginMsg, 384);
        $loginMsg = json_encode($loginMsg, JSON_UNESCAPED_UNICODE);
        return self::dbConn(self::$dbStLogin)->insertGetId([
            'staff_id' => $uid, 'loginMsg' => $loginMsg,
            'errMsg' => $errMsg, 'addtime' => toDate(),
        ]);
    }

    //UID获取权限
    public static function bomMenu($uid, $role_id)
    {
        $arys = [
            [
                'id' => 1, 'title' => '任务',
                'link' => '/h5/index.html',
                'icon0' => '/h5/imgs/con10.png',
                'icon1' => '/h5/imgs/con11.png',
            ],
            [
                'id' => 2, 'title' => '工作台',
                'link' => '/h5/workspace.html',
                'icon0' => '/h5/imgs/con20.png',
                'icon1' => '/h5/imgs/con21.png',
            ],
            [
                'id' => 3, 'title' => '统计',
                'link' => '/h5/tongji.html',
                'icon0' => '/h5/imgs/con30.png',
                'icon1' => '/h5/imgs/con31.png',
            ],
        ];
        return self::toback(0, '', $arys);
    }

    //工作台菜单
    public static function workspace($uid, $role_id)
    {
        //获取角色
        if ($uid || $role_id) {
            $uOne = (array) self::dbConn(self::$dbStaff)->where('id', $uid)->first();
            if (!$uOne) {
                return self::toback(-2, '员工不存在');
            }
            if (!$uOne['role_id']) {
                return self::toback(-2, '员工角色不存在');
            }
        }
        $isauth = 0; //0所有，1部门经理，2员工
        // 部门经理/员工
        if ($uOne['role_id']<4 && $uOne['depart_lead']==2) {
            $isauth = 1;
        }
        else if ($uOne['role_id']==4 && $uOne['depart_lead']==1) {
            $isauth = 2;
        }
        $act_ids = []; //权限ID集合
        if ($role_id > 2) {
            if ($isauth == 2) { //员工
                $authOnes = self::dbConn(self::$dbStAuth)
                    ->where('del', 0)
                    ->where('role_id', $role_id)
                    ->whereNotIn('action_id', [12,13,14,15])
                    ->get();
            } else { // 经理
                $authOnes = self::dbConn(self::$dbStAuth)
                    ->where('del', 0)
                    ->where('role_id', $role_id)
                    ->whereNotIn('action_id', [13,14,15])
                    ->get();
            }
            if (!count($authOnes)) {
                return self::toback(-2, '权限不存在');
            }
            foreach ($authOnes as $v) {
                $act_ids[] = $v->action_id;
                $actOne = self::dbConn(self::$dbStAction)
                    ->where('id', $v->action_id)
                    ->first();
                if (!empty($actPone) || !in_array($actOne->pid, $act_ids)) {
                    $act_ids[] = $actOne->pid;
                }
            }
            if (!count($act_ids)) {
                return self::toback(-2, '没有权限');
            }
        }
        // ddd($act_ids);
        //获取权限
        if ($act_ids) {
            $actOnes = self::dbConn(self::$dbStAction)
                ->where('h5show', 0)
                ->whereIn('id', $act_ids)
                ->where('pid', 0)
                ->get();
        } else {
            $actOnes = self::dbConn(self::$dbStAction)
                ->where('h5show', 0)
                ->where('pid', 0)
                ->get();
        }
        // ddd($actOnes);
        if (!count($actOnes)) {
            return self::toback(-2, '菜单不存在');
        }
        $actArys = []; //权限ID集合
        foreach ($actOnes as $v) {
            if ($act_ids) {
                $childs = self::dbConn(self::$dbStAction)
                    ->where('h5show', 0)
                    ->whereIn('id', $act_ids)
                    ->where('pid', $v->id)
                    ->orderBy('sort', 'desc')
                    ->get();
            } else {
                $childs = self::dbConn(self::$dbStAction)
                    ->where('h5show', 0)
                    ->where('pid', $v->id)
                    ->orderBy('sort', 'desc')
                    ->get();
            }
            $childList = [];
            if (count($childs)) {
                foreach ($childs as $vv) {
                    $childList[] = [
                        'id' => $vv->id, 'title' => $vv->title,
                        'link' => $vv->h5link, 'pid' => $vv->pid,
                        'icon' => $vv->h5icon,
                    ];
                }
            }
            $actArys[] = [
                'id' => $v->id, 'title' => $v->title,
                'childList' => $childList,
            ];
        }
        return self::toback(0, '', $actArys);
//        //获取项目配置
//        $configObj = file_get_contents('config.json');
//        if (!$configObj) {
//            return self::toback(-2, '配置错误');
//        }
//        $config = json_decode($configObj, true);
//        $config['guoqi'] = strtotime($config['period']) < time() ? false : true;
//        $ary = [
//            'act' => $actArys,
//            'config' => $config,
//        ];
//        return self::toback(0, '', $ary);
    }
}